/**
 * $http 的 promise 形式, 并且 then 只需要处理一个 function 即可(就有点类似 jq 中 ajax 请求的 complete)
 * eg:
 *     Ajax.get(url, data).then(function(result){console.log(result)})
 */
AModule.provider('A.Ajax', AjaxProvider);

function AjaxProvider() {

    this.$get = ['$q', '$http', 'STRINGS.DATA', function ($q, $http, STRINGS) {

        function Ajax(cfg) {

            var deferred = $q.defer();

            $http(cfg).then(function (res) {

                deferred.resolve(res.data);
            }, function (reason) {

                // 失败也使用 resolve 好处理点, 直接判断 result.success 的值
                deferred.resolve({
                    success: false,
                    msg: STRINGS.NETWORK_ERROR,
                    errors: reason
                });
            });

            return deferred.promise;
        }

        // 循环创建 get delete head jsonp 方法
        createShortMethods('get', 'delete', 'head', 'jsonp');

        createShortMethodsWithData('post', 'put', 'patch');

        function createShortMethods(names) {
            angular.forEach(arguments, function (name) {
                Ajax[name] = function (url, config) {

                    return Ajax(angular.extend({}, config || {}, {
                        method: name,
                        url: url
                    }));
                };
            });
        }

        function createShortMethodsWithData(name) {
            angular.forEach(arguments, function (name) {
                Ajax[name] = function (url, data, config) {

                    return Ajax(angular.extend({}, config || {}, {
                        method: name,
                        url: url,
                        data: data
                    }));
                };
            });
        }

        return Ajax;
    }];
}